package com.sqlparser;

import com.sqlparser.core.lexer.Lexer;
import com.sqlparser.core.lexer.impl.SimpleLexer;
import com.sqlparser.core.parser.Parser;
import com.sqlparser.core.parser.impl.SimpleParser;
import com.sqlparser.core.parser.ast.SQLStatement;
import com.sqlparser.core.executor.Executor;
import com.sqlparser.core.executor.impl.SimpleExecutor;
import com.sqlparser.storage.Storage;
import com.sqlparser.storage.impl.MemoryStorage;
import com.sqlparser.common.exception.SQLParserException;

import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * SQL解析器应用程序入口
 */
public class SQLParserApplication {
    private final Storage storage;
    private final Executor executor;
    
    public SQLParserApplication() {
        // 初始化存储引擎
        this.storage = new MemoryStorage();
        this.storage.initialize();
        
        // 初始化执行引擎
        this.executor = new SimpleExecutor(storage);
    }
    
    /**
     * 执行SQL查询
     */
    public List<Map<String, Object>> executeQuery(String sql) {
        try {
            // 词法分析
            Lexer lexer = new SimpleLexer(sql);
            
            // 语法分析
            Parser parser = new SimpleParser(lexer);
            SQLStatement stmt = parser.parse();
            
            // 执行查询
            return executor.execute(stmt);
            
        } catch (SQLParserException e) {
            System.err.println("Error executing query: " + e.getMessage());
            throw e;
        }
    }
    
    /**
     * 打印查询结果
     */
    private static void printResult(List<Map<String, Object>> result) {
        if (result.isEmpty()) {
            System.out.println("No results found.");
            return;
        }
        
        // 打印列头
        Map<String, Object> firstRow = result.get(0);
        firstRow.keySet().forEach(column -> System.out.printf("%-15s", column));
        System.out.println();
        
        // 打印分隔线
        firstRow.keySet().forEach(column -> System.out.print("---------------"));
        System.out.println();
        
        // 打印数据行
        for (Map<String, Object> row : result) {
            row.values().forEach(value -> System.out.printf("%-15s", value));
            System.out.println();
        }
    }
    
    public static void main(String[] args) {
        SQLParserApplication app = new SQLParserApplication();
        
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Simple SQL Parser (type 'exit' to quit)");
            System.out.println("Available table: users(id, name, age, salary, createDate)");
            System.out.println("Example: SELECT name, age FROM users WHERE age > 18");
            
            while (true) {
                System.out.print("\nSQL> ");
                String sql = scanner.nextLine().trim();
                
                if (sql.equalsIgnoreCase("exit")) {
                    break;
                }
                
                if (sql.isEmpty()) {
                    continue;
                }
                
                try {
                    List<Map<String, Object>> result = app.executeQuery(sql);
                    printResult(result);
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                }
            }
            
            System.out.println("Bye!");
        }
    }
} 